import { Form } from '@ant-design/compatible';
import AuthComponent from '@/components/Authorized/AuthComponent';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, Checkbox, Input, Select, Button } from 'antd';
import router from 'umi/router'
import React, { useState, useCallback, useRef, useEffect, memo } from 'react';
import ProTable from '@ant-design/pro-table';
import { useBoolean, useRequest } from '@umijs/hooks';
import { getCompensationCount } from '../../service';
import moment from 'moment';
import { connect } from 'dva';
import styles from './AuditForms.less';
import PayCountModal from './PayCountModal'

const { Option } = Select;

const plainOptions = [
  { label: '已出票旅客', value: '已出票' }, // Y 是   '' 否
  { label: '包含已取消旅客', value: '已取消' }, // Y 是   '' 否 
];


// 过滤证件类型
const flilterIDtype = (v) => {
  if (v === 'NI') {
    return (
      <span>身份证</span>
    )
  } else if (v === 'PP' || v === 'PSPT') {
    return (
      <span>护照</span>
    )
  } else {
    return (
      <span>其他</span>
    )
  }

}
let hiddenData = null
const TableList = (props) => {
  const { allDatas, allPassengersList, getPassengersList, getChildData, getFlightPaxInfoLoading } = props;
  // const { data: selectData } = useRequest(queryCityInfo); //获取出发和到达航站
  const [isCollapse, controlC] = useState(false); //搜索面板是否折叠
  const actionRef = useRef();
  const ref = useRef();
  const [allList, setAllList] = useState([])// 全部数据
  const [selectRow, setSelectRow] = useState(props.passengers)// 选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState(props.passengersIds)// 选中项的id
  const [cancelAndTicket, setCancelAndTicket] = useState(['已出票'])// 是否取消和是否出票
  const [checkedMans, setCheckedMans] = useState(0)// 已选旅客人数（包含婴儿）
  const [allMans, setAllMans] = useState(0)// 全部旅客人数（包含婴儿）
  const [segmentData, setSegmentData] = useState([])// 航段数据
  const [defaultSelectVal, setDefaultSelectVal] = useState("all")// 航段数据
  // 点击全部或者选中旅客 全部-false 选中旅客-true
  const { state: selectState, setTrue, setFalse } = useBoolean(false);

  // 得到最新的列表数据
  useEffect(() => {
    let checkArr = [];
    if (selectState) {
      setAllList(selectRow);
    } else {
      setAllList(allPassengersList);
    }
    let mans = 0; //所有计算人数
    for (let item of allPassengersList) {
      if (item.withBaby === 'Y') {
        mans += 1;
      }
    }
    setAllMans(mans + allPassengersList.length);

    let selectMans = 0; //计算选中人数
    for (let item of selectRow) {
      checkArr.push(item.idx);
      if (item.withBaby === 'Y') {
        selectMans += 1;
      }
    }
    setSelectedRowKeys(checkArr);
    setCheckedMans(selectMans + selectRow.length);
    setSelectRow(selectRow);
  }, [allPassengersList, selectRow])

  // 选中项
  const changeRows = (selectedRowKeys, selectedRows) => {
    let mans = 0; //计算人数
    for (let item of selectedRows) {
      if (item.withBaby === 'Y') {
        mans += 1;
      }
    }
    setCheckedMans(mans + selectedRows.length);
    // setSelectRow([...selectedRows]);
    // setSelectedRowKeys([...selectedRowKeys]);
  }
  // 用户手动选择/取消选择某行的回调
  const rowOnSelect = (record, selected, selectedRows, nativeEvent) => {
    let tempTableSelectIdx = JSON.parse(JSON.stringify(selectRow))
    if (selected) { //勾选
      tempTableSelectIdx.push(record);
    } else { //取消
      for (let i = 0; i < tempTableSelectIdx.length; i++) {
        if (tempTableSelectIdx[i].idx === record.idx) {
          tempTableSelectIdx.splice(i, 1);
          continue;
        }
      }
    }
    let checkArr = [];
    for (let item of tempTableSelectIdx) {
      checkArr.push(item.idx);
    }
    setSelectedRowKeys(checkArr);
    setSelectRow(tempTableSelectIdx);
    getChildData(checkArr, tempTableSelectIdx);

    // console.log('手动选择/取消record', record);
    // console.log('手动选择/取消selected', selected);
    // console.log('手动选择/取消selec2222222222', selectedRows);
  }
  // 用户手动选择/取消选择所有行的回调
  const rowOnSelectAll = (selected, record, selectedRows) => {
    let tempTableSelectIdx = JSON.parse(JSON.stringify(selectRow));
    if (tempTableSelectIdx.length === 0) {
      setSelectRow(record);
      if (selected) {
        tempTableSelectIdx = JSON.parse(JSON.stringify(record));
      }
    } else {
      if (selected) {
        for (const item of selectedRows) {
          tempTableSelectIdx.push(item);
        }
        setSelectRow(tempTableSelectIdx);
      } else {
        for (let i = 0; i < tempTableSelectIdx.length; i++) {
          for (let j = 0; j < selectedRows.length; j++) {
            if (tempTableSelectIdx[i] && tempTableSelectIdx[i].idx === selectedRows[j].idx) {
              tempTableSelectIdx.splice(i, 1);
            }
          }
        }
      }
      setSelectRow(tempTableSelectIdx);
    }
    let checkArr = [];
    for (let item of tempTableSelectIdx) {
      checkArr.push(item.idx);
    }
    setSelectedRowKeys(checkArr);
    getChildData(checkArr, tempTableSelectIdx);

    // console.log('所有行record', record);
    // console.log('所有行selected', selected);
    // console.log('所有行selectedRows', selectedRows);
  }
  // 多选的选中
  const changeCheckbox = (values) => {
    setCancelAndTicket([...values])
  }

  // 计算经停数据
  useEffect(() => {
    if (allDatas.ccode) { //存在经停
      if (allDatas.org === allDatas.acode) { // 前半段
        setSegmentData([
          { lable: "全部", value: "all_before" },
          { lable: `${allDatas.orgName}-${allDatas.dstName}`, value: "before" },
          { lable: `${allDatas.aname}-${allDatas.cname}`, value: "ac" }
        ]);
        setDefaultSelectVal("all_before");
      }
      if (allDatas.org === allDatas.bcode) { // 后半段
        setSegmentData([
          { lable: "全部", value: "all_after" },
          { lable: `${allDatas.orgName}-${allDatas.dstName}`, value: "after" },
          { lable: `${allDatas.aname}-${allDatas.cname}`, value: "ac" }
        ]);
        setDefaultSelectVal("all_after");
      }
    } else { //不存在经停
      setSegmentData([
        { lable: "全部", value: "all" },
        { lable: `${allDatas.orgName}-${allDatas.dstName}`, value: "all_b_a" }
      ]);
      setDefaultSelectVal("all");
    }

  }, [allDatas])

  // 选择航段
  const onChangeSegment = (val) => {
    setDefaultSelectVal(val);
  }
  // 搜索前的回调
  const beforeSearchSubmit = useCallback(params => {
    setFalse();
    let snapCancelAndTicket = cancelAndTicket;
    let snapSelectVal = defaultSelectVal;
    if (event && event.target && event.target.querySelector && event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
      snapCancelAndTicket = ['已出票'];
      snapSelectVal = segmentData && segmentData[0].value;
      setCancelAndTicket(snapCancelAndTicket);
      setDefaultSelectVal(snapSelectVal);
    };

    let destFlag = "";
    let origFlag = "";
    // 不是经停(all,all_b_a) 是经停选择航段（before，after）
    if (snapSelectVal === "all" ||
      snapSelectVal === "all_b_a" ||
      snapSelectVal === "before" ||
      snapSelectVal === "after") {
      destFlag = allDatas.dst;
      origFlag = allDatas.org;
    }
    // 选择AC段
    if (snapSelectVal === "ac") {
      destFlag = allDatas.ccode;
      origFlag = allDatas.acode;
    }
    // 是经停
    // 前半段的全部
    if (snapSelectVal === "all_before") {
      destFlag = "";
      origFlag = allDatas.org;
    }
    // 后半段的全部
    if (snapSelectVal === "all_after") {
      destFlag = allDatas.dst;
      origFlag = "";
    }
    params.flightStart = params.flightStart && params.flightStart.format('YYYY-MM-DD HH:mm');
    params.flightEnd = params.flightEnd && params.flightEnd.format('YYYY-MM-DD HH:mm');
    let fixedParams = {
      dest: destFlag, //到达航站
      flightNumber: allDatas.flightNumber, //航班号
      orig: origFlag, //起始航班
      flightStartDate: allDatas.flightDate, //航班起始日期
      flightEndDate: allDatas.flightDate, //航班到达日期
      ticketBeginDate: params.flightStart,
      ticketEndDate: params.flightEnd,
      isCancel: (snapCancelAndTicket.indexOf('已取消') > -1) ? "" : "N", //是否取消
      isPrintTktNo: (snapCancelAndTicket.indexOf('已出票') > -1) ? "Y" : "", //是否出票
      current: 1,
      pageSize: 1000,
    }
    // 搜索函数
    getPassengersList(Object.assign(fixedParams, params));
  }, [cancelAndTicket, defaultSelectVal, segmentData]);

  const [passengerName, handlePassengerName] = useState('')
  const [payCountVisible, handlePayCountVisible] = useState(false) // 总补偿人数弹框
  const [data, handleData] = useState([])
  const openCountModal = (payCount, record) => {
    if (payCount === '0') {
      return false;
    }
    handlePassengerName(record.psgName)
    handlePayCountVisible(true);
    getCompensationCount({
      flightNo: record.flightNum,
      flightDate: record.flightDate,
      paxId: record.idx
    }).then(res => {
      handleData(res)
    })
  };

  const columns = [
    {
      title: (_, type) => (type === 'table' ? '姓名' : '旅客姓名'),
      width: 120,
      key: "passengerName",
      fixed: 'left',
      order: 5,
      dataIndex: 'psgName',
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return <Input {...rest} placeholder="请输入旅客姓名" />;
      },
      render: (text, record) => {
        return (
          <div>
            {record.colorSign ? (<span style={{ color: "red" }}>{text}</span>) : <span>{text}</span>}
            {record.withBaby === "Y" ? (<img alt="" style={{ verticalAlign: 'middle' }} src={require('../images/icon-test.svg')} />) : null}
            {record.isChild === "Y" ? (<img alt="" style={{ verticalAlign: 'middle' }} src={require('../images/ertong.svg')} />) : null}
          </div>
        )
      }
    },
    {
      title: '旅客搜索',
      key: 'keySearch', //旅客搜索字段
      hideInTable: true,
      width: 120,
      order: 6,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return <Input {...rest} placeholder="证件号/票号" />;
      },
    },
    {
      title: '值机状态',
      dataIndex: 'checkStatus',
      width: 120,
      order: 4,
      hideInTable: true,
      renderFormItem: (_, { onChange, value = '' }) => (
        <Select value={value} onChange={onChange} placeholder="请选择值机状态">
          <Option value="">全部</Option>
          <Option value="PT">PT（出票）</Option>
          <Option value="NA">NA（未值机）</Option>
          <Option value="AC">AC（值机）</Option>
          <Option value="XR">XR（值机取消）</Option>
          <Option value="CL">CL（订座取消）</Option>
          <Option value="SB">SB（候补）</Option>
          <Option value="DL">DL（拉下）</Option>
        </Select>
      ),
    },
    {
      title: '航段选择',
      dataIndex: 'segmentSelect',
      width: 120,
      order: 3,
      hideInTable: true,
      renderFormItem: (_, { onChange, value = '' }) => (
        <Select value={defaultSelectVal} onChange={onChangeSegment} placeholder="请选择航段">
          {
            segmentData && segmentData.map(v => (<Option key={v.lable} value={v.value}>{v.lable}</Option>))
          }
        </Select>
      ),
    },
    {
      title: '证件类型',
      dataIndex: 'idType',
      fixed: 'left',
      width: 90,
      hideInSearch: true,
      render: text => {
        return flilterIDtype(text)
      }
    },
    {
      title: '结束购票时间',
      dataIndex: 'printTicketTime',
      key: "flightEnd",
      hideInTable: true,
      order: 1,
      width: 150,
      renderFormItem: (_, { ...rest }) => {
        return (
          <DatePicker
            showTime={{ format: 'HH:mm' }}
            disabledDate={(current) => { return current && current < ref.current.getFieldsValue().flightStart }}
            style={{ width: '100%' }}
            format='YYYY-MM-DD HH:mm'
            {...rest}
          />
        );
      },
    },
    {
      title: '证件号',
      fixed: 'left',
      key: 'idNum',
      hideInSearch: true,
      ellipsis: true,
      filters: false,
      dataIndex: 'idNum',
      width: 180,
    },
    {
      title: (_, type) => (type === 'table' ? '购票时间' : '起始购票时间'),
      dataIndex: 'printTicketTime',
      fixed: 'left',
      key: "flightStart",
      order: 2,
      width: 170,
      renderFormItem: (_, { ...rest }) => {
        return (
          <DatePicker
            showTime={{ format: 'HH:mm' }}
            disabledDate={(current) => { return current && current > ref.current.getFieldsValue().flightEnd }}
            style={{ width: '100%' }}
            format='YYYY-MM-DD HH:mm'
            {...rest}
          />
        );
      },
    },
    {
      title: '旅客手机号',
      ellipsis: true,
      key: 'phone',
      filters: false,
      hideInSearch: true,
      dataIndex: 'phone',
      width: 120,
      render:(_) => {
        return <div style={{height:"6px"}} >{_}</div>
      },
    },
    {
      title: '航段',
      hideInSearch: true,
      dataIndex: 'segment',
      valueType: "segment",
      width: 130
    },
    {
      title: '总补偿次数',
      hideInSearch: true,
      dataIndex: 'payCount',
      width: 130,
      render: (payCount, record) => (
        <span style={{ textDecoration: 'underline' }} onClick={() => {
          openCountModal(payCount, record)
        }} className={payCount !== '0' ? styles.count : ''}>{payCount == '-' ? 0 : payCount}</span>
      )
    },
    {
      title: '总补偿金额',
      hideInSearch: true,
      dataIndex: 'payMoney',
      width: 130
    },
    {
      title: '票号',
      hideInSearch: true,
      dataIndex: 'etNum',
      width: 130
    },
  ];
  return (
    <div className={styles.editPassengerTableList}>
      <ProTable
        options={false}
        size='small'
        dataSource={allList}
        className={`${styles.oversaleTable} collapse}`}
        scroll={{ x: 1000, y: 300 }}
        headerTitle={
          <span style={{ paddingRight: 10, color: "#000" }}>全部航班列表</span>
        }
        search={{
          collapsed: false, //默认展开
          collapseRender: () => false, //不要折叠按钮
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 8,
            lg: 8,
            xl: 8,
            xxl: 8,
          }
        }}
        actionRef={actionRef}
        formRef={ref}
        loading={getFlightPaxInfoLoading}
        dateFormatter="YYYY-MM-DD"
        pagination={false}
        rowKey="idx"
        headerTitle={ //自定义表头
          <div style={{ fontWeight: 400, marginTop: "24px" }}>
            <div className={styles.checkBoxStyle}>
              <Checkbox.Group options={plainOptions} value={cancelAndTicket} onChange={changeCheckbox} />
            </div>
            <div>
              <span onClick={() => { setTrue(); setAllList(selectRow) }} className={styles.splitLine}>已选旅客{checkedMans}人</span>
              <span onClick={() => { setFalse(); setAllList(allPassengersList) }} className={styles.allList}>全部旅客{allMans}人</span>
            </div>
          </div>
        }
        beforeSearchSubmit={beforeSearchSubmit}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: changeRows,
          onSelect: rowOnSelect,
          onSelectAll: rowOnSelectAll
        }}
        tableAlertRender={(props) => {
          return false
        }}
      />
      <PayCountModal data={data} passengerName={passengerName} payCountVisible={payCountVisible} handlePayCountVisible={handlePayCountVisible}></PayCountModal>
    </div>
  );
};

/**
 * 优化渲染
 */
function carefulRender(prevProps, nextProps) {
  if (prevProps.allPassengersList.length == nextProps.allPassengersList.length) {
    return true
  } else {
    if (JSON.stringify(prevProps.allPassengersList.sort()) != JSON.stringify(nextProps.allPassengersList.sort())) {
      return false
    } else {
      return true
    }
  }
}

export default connect(state => state.auditDetail)(memo(TableList), carefulRender);
